package com.xxd.dfs.namenode;

import com.xxd.dfs.namenode.rpc.service.NameNodeServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author: XiaoDong.Xie
 * @create: 2020-08-18 10:00
 * @description:
 */
public class NameNodeRpcProto {

    private final Logger logger = LoggerFactory.getLogger(NameNodeRpcProto.class);
    private int port = Integer.parseInt(Configuration.getInstance().get("namenode.port"));

    private Server server = null;

    private FSNameSystem nameSystem;

    public NameNodeRpcProto(FSNameSystem nameSystem) {
        this.nameSystem = nameSystem;
    }

    public void start() throws IOException {
        // 启动一个rpc server，监听指定的端口号
        // 同时绑定好了自己开发的接口
        server = ServerBuilder
                .forPort(port)
                .addService(NameNodeServiceGrpc.bindService(new NameNodeRpcServer(nameSystem)))
                .build()
                .start();

        logger.info("NameNodeRpc 服务启动，监听端口号：" + port);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                NameNodeRpcProto.this.stop();
            }
        });
    }

    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
